package color.koitq.picker.fragment

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import butterknife.OnClick
import color.koitq.picker.R
import color.koitq.picker.activty.HomeColorListActivity
import color.koitq.picker.activty.InspirationActivity
import color.koitq.picker.ad.AdFragment
import color.koitq.picker.adapter.Tab3Adapter
import color.koitq.picker.entity.Tab3Model
import color.koitq.picker.util.SQLdm
import color.koitq.picker.util.Util
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import kotlinx.android.synthetic.main.fragment_tab3.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.support.v4.startActivity
import org.litepal.LitePal
import java.util.*
import kotlin.concurrent.thread

class Tab3Frament : AdFragment() {
    private var mView: View? = null
    private lateinit var mAdapter:Tab3Adapter
    private var model:Tab3Model?=null
    private  var tab3Models=mutableListOf<Tab3Model>()
    override fun getLayoutId(): Int {
        return R.layout.fragment_tab3
    }

    override fun initKotlinWidget() {
        super.initKotlinWidget()
        topbar!!.setTitle("灵感")
        initList()
        click.setOnClickListener {
            mView=it
            showVideoAd()
        }
    }


    private fun initList() {
        list.layoutManager=StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        mAdapter=Tab3Adapter()
        list.adapter=mAdapter
        mAdapter.setOnItemClickListener { adapter, view, position ->
            model=mAdapter.getItem(position)
            showVideoAd()
        }
      var models=  LitePal.findAll(Tab3Model::class.java)
        if (models.isNullOrEmpty()) {
            loadData()
        }else {
            mAdapter.setNewInstance(models)
        }
    }

    private fun loadData() {
        thread {
            val imgs = SQLdm.queryImgs("创意")
            for (img in imgs) {
                Glide.with(requireActivity()).asBitmap().load(img).into(object : CustomTarget<Bitmap?>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap?>?
                    ) {
                        showBitmapColor(resource,img)
                        var models=  LitePal.findAll(Tab3Model::class.java)
                        requireActivity().runOnUiThread{
                            mAdapter.setNewInstance(models)
                        }
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {

                    }
                })
            }
        }

    }

    /**
     * 随机取5个像素点，获取颜色
     */
    fun showBitmapColor(bitmap: Bitmap,path:String) {
        val bitWidth = bitmap.width
        val bitHeight = bitmap.height
        val pixels = IntArray(bitWidth * bitHeight) //保存所有的像素的数组，图片宽×高
        bitmap.getPixels(pixels, 0, bitWidth, 0, 0, bitWidth, bitHeight)
        val countList = mutableListOf<Int>()
        val diff = pixels.size / 5

        for (i in 1..5) {
            val a = Random().nextInt(diff * i)
            countList.add(a)

        }
        var model = Tab3Model()
        model.img=path
        var tag = 0
        for (i in countList) {
            tag++
            val clr = pixels[i]
            val red = clr and 0x00ff0000 shr 16 //取高两位
            val green = clr and 0x0000ff00 shr 8 //取中两位
            val blue = clr and 0x000000ff //取低两位
            val colorStr = Util.rgbToHex(red, green, blue)
            when (tag) {
                1 -> model.color1 = colorStr
                2 -> model.color2 = colorStr
                3 -> model.color3 = colorStr
                4 -> model.color4 = colorStr
                5 -> model.color5 = colorStr
            }
        }
        model.save()
        tab3Models.add(model)
    }

    override fun fragmentAdClose() {
        topbar!!.post {
            if (mView != null) {
                startActivity<InspirationActivity>()
            }else if (model != null) {
                startActivity<HomeColorListActivity>("model" to model)
            }
            mView=null
            model=null
        }
    }
}